from time import timezone
from django.db import models
from django.utils.translation import gettext_lazy as _
from apps.chefs.models import DjChef  # 假设您已经创建了DjChef模型

class DjNotificationType(models.Model):
    """
    通知类型模型 定义各类通知的模板和行为
    """
    name = models.CharField(
        max_length=50,
        verbose_name='类型名称'
    )
    code = models.SlugField(
        max_length=50,
        unique=True,
        verbose_name='类型代码'
    )
    template = models.TextField(
        verbose_name='消息模板',
        help_text='可使用{var}作为变量占位符'
    )
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否启用'
    )
    push_enabled = models.BooleanField(
        default=True,
        verbose_name='是否推送'
    )
    icon = models.CharField(
        max_length=50,
        blank=True,
        verbose_name='图标类名'
    )
    priority = models.PositiveSmallIntegerField(
        default=0,
        verbose_name='优先级',
        help_text='数字越大优先级越高'
    )
    
    class Meta:
        verbose_name = '通知类型'
        verbose_name_plural = '通知类型'
        ordering = ['-priority', 'name']
    
    def __str__(self):
        return self.name


class DjNotification(models.Model):
    """
    厨师通知模型 记录所有发给厨师的通知
    """
    STATUS_CHOICES = (
        ('unread', '未读'),
        ('read', '已读'),
        ('deleted', '已删除'),
    )
    
    chef = models.ForeignKey(
        DjChef,
        on_delete=models.CASCADE,
        related_name='notifications',
        verbose_name='关联厨师'
    )
    notification_type = models.ForeignKey(
        DjNotificationType,
        on_delete=models.PROTECT,
        related_name='notifications',
        verbose_name='通知类型'
    )
    
    # 内容字段
    title = models.CharField(
        max_length=100,
        verbose_name='通知标题'
    )
    content = models.TextField(
        verbose_name='通知内容'
    )
    data = models.JSONField(
        default=dict,
        blank=True,
        verbose_name='附加数据'
    )
    
    # 状态管理
    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='unread',
        verbose_name='状态'
    )
    is_pushed = models.BooleanField(
        default=False,
        verbose_name='是否已推送'
    )
    
    # 关联业务
    related_object_id = models.PositiveIntegerField(
        null=True,
        blank=True,
        verbose_name='关联对象ID'
    )
    related_object_type = models.CharField(
        max_length=50,
        blank=True,
        verbose_name='关联对象类型'
    )
    
    # 时间字段
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='创建时间'
    )
    read_at = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='阅读时间'
    )
    
    class Meta:
        verbose_name = '厨师通知'
        verbose_name_plural = '厨师通知'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['chef', 'status']),
            models.Index(fields=['related_object_type', 'related_object_id']),
        ]
    
    def __str__(self):
        return f"{self.chef} - {self.title}"
    
    def mark_as_read(self, save=True):
        """标记为已读"""
        if self.status != 'read':
            self.status = 'read'
            self.read_at = timezone.now()
            if save:
                self.save(update_fields=['status', 'read_at'])
    
    def mark_as_deleted(self, save=True):
        """标记为已删除"""
        if self.status != 'deleted':
            self.status = 'deleted'
            if save:
                self.save(update_fields=['status'])
    
    @classmethod
    def create_notification(cls, chef, notification_type_code, context=None, related_object=None):
        """
        创建通知的快捷方法
        :param chef: 接收通知的厨师
        :param notification_type_code: 通知类型代码
        :param context: 模板上下文变量
        :param related_object: 关联的业务对象
        """
        from django.template import Template, Context
        
        try:
            notification_type = DjNotificationType.objects.get(code=notification_type_code)
        except DjNotificationType.DoesNotExist:
            return None
        
        context = context or {}
        template = Template(notification_type.template)
        content = template.render(Context(context))
        
        notification = cls(
            chef=chef,
            notification_type=notification_type,
            title=notification_type.name,
            content=content,
            status='unread'
        )
        
        if related_object:
            notification.related_object_id = related_object.id
            notification.related_object_type = related_object.__class__.__name__.lower()
        
        notification.save()
        return notification


class DjNotificationPreference(models.Model):
    """
    厨师通知偏好设置
    """
    chef = models.OneToOneField(
        DjChef,
        on_delete=models.CASCADE,
        related_name='notification_preferences',
        verbose_name='关联厨师'
    )
    enabled_types = models.ManyToManyField(
        DjNotificationType,
        blank=True,
        verbose_name='启用的通知类型'
    )
    push_enabled = models.BooleanField(
        default=True,
        verbose_name='启用推送'
    )
    email_enabled = models.BooleanField(
        default=False,
        verbose_name='启用邮件通知'
    )
    sms_enabled = models.BooleanField(
        default=False,
        verbose_name='启用短信通知'
    )
    mute_until = models.DateTimeField(
        null=True,
        blank=True,
        verbose_name='静默直到'
    )
    
    class Meta:
        verbose_name = '通知偏好设置'
        verbose_name_plural = '通知偏好设置'
    
    def __str__(self):
        return f"{self.chef} 的通知偏好"
    
    def is_type_enabled(self, notification_type_code):
        """检查特定通知类型是否启用"""
        return self.enabled_types.filter(code=notification_type_code).exists()


class DjPushDevice(models.Model):
    """
    推送设备模型 用于消息推送集成
    """
    PLATFORM_CHOICES = (
        ('ios', 'iOS'),
        ('android', 'Android'),
        ('web', 'Web'),
        ('mini_program', '微信小程序'),
    )
    
    chef = models.ForeignKey(
        DjChef,
        on_delete=models.CASCADE,
        related_name='push_devices',
        verbose_name='关联厨师'
    )
    platform = models.CharField(
        max_length=20,
        choices=PLATFORM_CHOICES,
        verbose_name='平台'
    )
    device_token = models.CharField(
        max_length=255,
        unique=True,
        verbose_name='设备令牌'
    )
    is_active = models.BooleanField(
        default=True,
        verbose_name='是否激活'
    )
    app_version = models.CharField(
        max_length=20,
        blank=True,
        verbose_name='应用版本'
    )
    os_version = models.CharField(
        max_length=20,
        blank=True,
        verbose_name='系统版本'
    )
    language = models.CharField(
        max_length=10,
        default='zh-cn',
        verbose_name='语言偏好'
    )
    created_at = models.DateTimeField(
        auto_now_add=True,
        verbose_name='注册时间'
    )
    last_active_at = models.DateTimeField(
        auto_now=True,
        verbose_name='最后活跃时间'
    )
    
    class Meta:
        verbose_name = '推送设备'
        verbose_name_plural = '推送设备'
        unique_together = [['chef', 'device_token']]
    
    def __str__(self):
        return f"{self.chef} 的 {self.get_platform_display()} 设备"